import React from "react";
import {SortOrder, TablePaginationConfig} from "antd/lib/table/interface";
import ProTable from "@ant-design/pro-table";
import {TableProps} from "antd/lib/table";
import {ProColumns, RequestData} from "@ant-design/pro-table/lib/typing";
import {GetRowKey} from "rc-table/lib/interface";

interface Props{
  columns?: ProColumns<any, any>[];
  onChange?:(value:string[] | number[])=>void;
  value?:string[]|number[];
  params?:any;
  /** @name 一个获得 dataSource 的方法 */
  request?: (params: any & {
    pageSize?: number;
    current?: number;
    keyword?: string;
  }, sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => Promise<Partial<RequestData<any>>>;
  pagination?: false | TablePaginationConfig;
  rowKey:string | GetRowKey<any>;
}

interface State {
  selectedRowKeys:string[]|number[];
}

export default class FormTable extends React.Component<Props, State> {

  state={
    selectedRowKeys:[]
  }

  static getDerivedStateFromProps(nextProps: Props) {
    if ('value' in nextProps) {
      return { selectedRowKeys: nextProps.value || [] };
    }
    return null;
  }

  onChange=(selectedRowKeys: any[], selectedRows: any[]) =>{
    const {onChange}=this.props;
    if (onChange) {
      onChange(selectedRowKeys);
    }
  }

  render() {
    const {
      columns,params,request,pagination,rowKey
    }=this.props;

    const {selectedRowKeys}=this.state;

    const rowSelection:TableProps<any>['rowSelection']={
      selectedRowKeys:selectedRowKeys,
      onChange:this.onChange
    }

    return (
      <ProTable<any>
        rowKey={rowKey}
        size={'small'}
        params={params}
        search={false}
        toolBarRender={false}
        request={request}
        columns={columns}
        pagination={pagination}
        rowSelection={rowSelection}
      />
    );
  }
}
